package com.blinddate.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blinddate.context.BaseContext;
import com.blinddate.pojo.entity.GoodsType;
import com.blinddate.pojo.entity.Orders;
import com.blinddate.pojo.entity.ShopInf;
import com.blinddate.pojo.result.Result;
import com.blinddate.pojo.vo.SalesVolumeVO;
import com.blinddate.service.GoodsTypeService;
import com.blinddate.service.OrdersService;

import com.blinddate.service.ShopInfService;
import com.blinddate.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("user/order")
@Slf4j
@Api(tags = "订单相关接口")
public class OrderController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private UserService userService;

    @Autowired
    private GoodsTypeService goodsTypeService;

    @Autowired
    private ShopInfService shopInfService;


    //判断权限

    @GetMapping("/get_order_list")
    @ApiOperation("获取订单列表")
    public Result<List<Orders>> getOrderList(@RequestParam Integer page,@RequestParam Integer size){
        log.info("获取订单列表,参数page:{},size:{}",page,size);
        //判断用户权限
        Boolean decide = userService.identityDecide();
        if (!decide){
            return Result.error("用户权限不够");
        }

        IPage<Orders> iPage = new Page<>(page,size);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        ordersService.page(iPage,ordersLambdaQueryWrapper);
        List<Orders> records = iPage.getRecords();
        if (records.size()==0){
            return Result.error("暂无订单");
        }
        return Result.success(records);
    }

    @GetMapping("/get_self_orders")
    @ApiOperation("获取用户自己的订单")
    public Result<List<Orders>> getSelfOrders(@RequestParam Integer page,@RequestParam Integer size){
        log.info("获取用户自己的订单,参数page:{},size:{}",page,size);
        Long userId = BaseContext.getCurrentId();
        List<Orders> listToUserId = getListToUserId(userId, page, size);
        if (listToUserId.size()==0){
            return Result.error("你尚未购买过产品");
        }
        return Result.success(listToUserId);
    }

    public List<Orders> getListToUserId(Long userId, Integer page,Integer size){//获取订单列表
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId,userId);
        IPage<Orders> iPage = new Page<>(page,size);
        ordersService.page(iPage,ordersLambdaQueryWrapper);
        return iPage.getRecords();
    }

    @GetMapping("/get_by_outtradeno")
    @ApiOperation("根据订单号进行查询")
    public Result<Orders> getByOuttradeno(String outTradeNo){
        log.info("根据订单号进行查询,参数outTradeNo:{}",outTradeNo);
        //判断用户权限
        Boolean decide = userService.identityDecide();
        if (!decide){
            return Result.error("用户权限不够");
        }

        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getOutTradeNo,outTradeNo);
        Orders orders = ordersService.getOne(ordersLambdaQueryWrapper);
        if (orders==null){
            return Result.error("没有该订单");
        }
        return Result.success(orders);
    }

    @GetMapping("get_by_userId")
    @ApiOperation("根据用户id进行查询")
    public Result<List<Orders>> getByUserId(Long userId,@RequestParam Integer page,@RequestParam Integer size){
        log.info("根据用户id进行查询,参数userId:{},page:{},size:{}",userId,page,size);
        //判断用户权限
        Boolean decide = userService.identityDecide();
        if (!decide){
            return Result.error("用户权限不够");
        }
        List<Orders> listToUserId = getListToUserId(userId, page, size);
        if (listToUserId.size()==0){
            return Result.error("暂无订单");
        }
        return Result.success(listToUserId);
    }

    @GetMapping("/get_orders_like")
    @ApiOperation("获取模糊信息的的订单")//vague  模糊
    public Result<List<Orders>> getOrdersLike(String vague,@RequestParam Integer page,@RequestParam Integer size){
        log.info("获取模糊信息的的订单,参数vague:{},page:{},size:{}",vague,page,size);
        //判断用户权限
        Boolean decide = userService.identityDecide();
        if (!decide){
            return Result.error("用户权限不够");
        }

        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.like(Orders::getUserId,vague).or().like(Orders::getOutTradeNo,vague);
        IPage<Orders> iPage = new Page<>(page,size);
        ordersService.page(iPage,ordersLambdaQueryWrapper);
        List<Orders> records = iPage.getRecords();
        if (records.size()==0){
            return Result.error("没有查询到");
        }
        return Result.success(records);
    }

    @PostMapping("/admin_update_orders")
    @ApiOperation("商品订单退款")
    public Result<String> adminUpdateOrders(String outTradeNo){
        log.info("修改订单信息,参数outTradeNo:{}",outTradeNo);  //修改订单状态
        //判断用户权限
        Boolean decide = userService.identityDecide();
        if (!decide){
            return Result.error("用户权限不够");
        }
        LambdaUpdateWrapper<Orders> ordersLambdaUpdateWrapper1 = new LambdaUpdateWrapper<>();
        ordersLambdaUpdateWrapper1.eq(Orders::getOutTradeNo,outTradeNo);
        Orders orders = ordersService.getOne(ordersLambdaUpdateWrapper1);
        if (orders==null){
            return Result.error("没有该商品");
        }

        //更新状态
        LambdaUpdateWrapper<Orders> ordersLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        ordersLambdaUpdateWrapper.eq(Orders::getOutTradeNo,outTradeNo).set(Orders::getStatus,Orders.REFUND);
        boolean update = ordersService.update(ordersLambdaUpdateWrapper);
        if (update){
            return Result.success("更新成功");
        }
        return Result.error("更新失败");

    }

    //超级管理员获取指定天数所有订单记录
    @GetMapping("/super_get_orders_total")
    @ApiOperation("获取指定天数所有商品的销售额")
    public Result<List<SalesVolumeVO>> superGetOrdersTotal(Integer day){
        log.info("获取指定天数所有商品的销售额,day:{}",day);
        Boolean superAdmin = userService.superAdmin();
        if (!superAdmin){
            return Result.error("用户权限不够");
        }

        if (day==0||day==null){
            day = ordersService.getMorTime(0L);
        }

        List<GoodsType> list = goodsTypeService.list();
        List<SalesVolumeVO> salesVolumeVOList = new ArrayList<>();
        for (GoodsType goodsType : list) {
            Long orderCount = ordersService.getAllCount(day, goodsType.getId());
            if (orderCount != 0) {
                extracted(day, salesVolumeVOList, goodsType, orderCount);
            }
        }
        if (salesVolumeVOList.size()>0){
            return Result.success(salesVolumeVOList);
        }
        return Result.error("该时间段内暂时没有消费");
    }

    @GetMapping("/admin_get_orders_total")
    @ApiOperation("获取指定天数到今天的所有商品销售额")
    public Result<List<SalesVolumeVO>> adminGetOrdersTotal(Long shopId,Integer day){
        log.info("获取指定天数到今天的所有商品销售额,shopId:{},day:{}",shopId,day);  //修改订单状态
        //判断用户权限
        Boolean decide = userService.identityDecide();
        if (!decide){
            return Result.error("用户权限不够");
        }


        if (day==0||day==null){
            day = ordersService.getMorTime(shopId);
        }

        ShopInf shopInf = shopInfService.getById(shopId);
        if (shopInf==null){
            return Result.error("没有该店面信息");
        }

        List<GoodsType> list = goodsTypeService.list();
        List<SalesVolumeVO> salesVolumeVOList = new ArrayList<>();
        for (GoodsType goodsType :list) {
            Long orderCount = ordersService.getCount(day, shopId, goodsType.getId());
            if (orderCount!=0){
                extracted(day, salesVolumeVOList, goodsType, orderCount);
            }
        }
        if (salesVolumeVOList.size()>0){
            return Result.success(salesVolumeVOList);
        }
        return Result.error("本店面在该时间段内未有消费");
    }

    //用于记录
    private void extracted(Integer day, List<SalesVolumeVO> salesVolumeVOList, GoodsType goodsType, Long orderCount) {
        SalesVolumeVO salesVolumeVO = new SalesVolumeVO();
        salesVolumeVO.setPaytotal(orderCount * goodsType.getTotal());
        salesVolumeVO.setDay(goodsType.getDay());
        salesVolumeVO.setCount(goodsType.getCount());
        Integer type = goodsType.getType();
        salesVolumeVO.setGoodsType(type);
        salesVolumeVO.setStartTime(LocalDateTime.now());
        salesVolumeVO.setEndime(LocalDateTime.now().minusDays(day));
        salesVolumeVO.setTotal(orderCount);
        String des = "商品类型不详";
        //获取到day和count  两个不能同时有值
        Integer goodsTypeDay = goodsType.getDay();
        Integer goodsTypeCount = goodsType.getCount();

        if (type.equals(GoodsType.Green_VIP)) {
            des = goodsTypeDay + "天绿卡会员";
        } else if (type.equals(GoodsType.VIP)) {
            des = goodsTypeDay + "天vip会员";
        } else if (type.equals(GoodsType.SHOW_VIP)) {
            des = goodsTypeDay + "天展示会员";
        } else if (type.equals(GoodsType.COUNT)) {
            des = goodsTypeCount + "个开锁次数";
        }
        salesVolumeVO.setGoodsDis(des);
        salesVolumeVOList.add(salesVolumeVO);
    }

}
